package com.transaction.util;

import com.sun.org.apache.bcel.internal.generic.RET;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * Created with LXD
 *
 * @author:Luhui
 * @qq:729913162
 * @Date:2018-09-22
 * @Time:13:15
 */
public class SuperTransactionInterceptor implements MethodInterceptor {


    @Autowired
    private SuperTransactionProcessor superTransactionProcessor;
    @Autowired
    private TransactionTemplate transactionTemplate;



    @Override
    public Object intercept(Object o, final Method method,final Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib....");
        //先判断此方法是否需要进行事务加强
        Set<Method> methods = superTransactionProcessor.getTransactionMethodMap().get(o.getClass().getSuperclass());
        for (Method method1 : methods) {
            System.out.println(method1.getName());
        }
        final Object target = superTransactionProcessor.getTransactionMethodObj().get(o.getClass().getSuperclass());
        if(superTransactionProcessor.getTransactionMethodMap().get(o.getClass().getSuperclass()).contains(method)){
            //需要进行事务增强
            System.out.println("事务代理执行");
            return transactionTemplate.execute(new TransactionCallback<Object>() {

                @Override
                public Object doInTransaction(TransactionStatus status) {

                    try {
                        return methodProxy.invokeSuper(o,objects);
                    } catch (Throwable throwable) {
                        throwable.printStackTrace();
                    }

                    return null;
                }
            });
        }else{
            //不需要
            return methodProxy.invokeSuper(o,objects);
        }

//        Map<Class<?>, Set<Method>> transactionMethodMap = superTransactionProcessor.getTransactionMethodMap();
//        Object retVal = null;
//        if(transactionMethodMap.get(o).contains(method)){
//            System.out.println("开始动态代理。。。");
//            retVal = methodProxy.invokeSuper(o, objects);
//
//        }
//        System.out.println("method:"+method.getName());
//
//        System.out.println("methodProxy:"+methodProxy.getSuperName());


//        return retVal;
    }


}
